<template>
  <div class="create-post">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <button class="back-button" @click="goBack">
        <span class="back-arrow">←</span>
      </button>
      <button class="publish-button" @click="pulish()">
        <span class="publish-icon">✈️</span>
        发布
      </button>
    </div>

    <!-- 主要内容区 -->
    <div class="content-area">
      <!-- 话题标签 -->
      <div class="topic-tag">
        <span class="hash">#</span>
        旅行中的你
      </div>

      <!-- 描述文本 -->
      <div class="description-text" contenteditable="true">
        每一个日常都值得被记录
        <br />
        记录日常、倾诉心声，邂逅美好~
      </div>

      <!-- 媒体上传区 -->
      <div class="media-upload">
        <!-- 预览容器 -->
        <div v-if="previewUrl" class="preview-container">
          <img v-if="mediaType === 'image'" :src="previewUrl" alt="预览" />
          <video v-else controls :src="previewUrl"></video>
          <button class="clear-button" @click="clearPreview">×</button>
        </div>
        <!-- 图片上传网格 -->
        <!-- 修改media-upload区域 -->
        <!-- 修改media-upload区域 -->
        <div class="media-upload">
          <div class="media-container">
            <!-- 已上传内容 -->
            <div v-for="(item, index) in mediaItems" :key="index" class="media-item">
              <img v-if="item.type === 'image'" :src="item.url" alt="图片">
              <video v-else controls :src="item.url"></video>
              <button class="delete-button" @click.stop="removeMedia(index)">×</button>
            </div>

            <!-- 单个上传按钮 -->
            <div v-if="mediaItems.length < 6" class="media-item upload-box" @click="openMediaPicker">
              <div class="plus-icon">+</div>
              <div class="upload-text">{{ }}</div>
            </div>
          </div>

          <input ref="fileInput" type="file" accept="image/*, video/*" style="display: none" @change="handleFileSelect"
            multiple>
        </div>

        <!-- 隐藏的文件输入 -->
      </div>

      <!-- 位置选择器 -->
      <div class="location-selector">
        <div class="location-icon">📍</div>
        <div class="location-text">你在哪里</div>
        <div class="arrow-right">›</div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-toolbar">
      <button class="tool-button" @click="startCamera('photo')">
        <div class="tool-icon">📸</div>
      </button>
      <button class="tool-button" @click="openMediaPicker">
        <div class="tool-icon">🖼️</div>
      </button>
      <button class="tool-button" @click="startCamera('video')">
        <div class="tool-icon">🎥</div>
      </button>
      <button class="tool-button">
        <div class="tool-icon">#️⃣</div>
      </button>
    </div>

    <!-- 相机界面 -->
    <div v-if="isCameraActive" class="camera-overlay">
      <video ref="videoPreview" autoplay playsinline></video>
      <div class="camera-controls">
        <button v-if="mediaMode === 'photo'" @click="capturePhoto">拍摄</button>
        <button v-else @click="toggleRecording">
          {{ isRecording ? '停止' : '开始' }}
        </button>
        <button @click="stopCamera">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const router = useRouter()

// 响应式状态
const fileInput = ref(null)
const videoPreview = ref(null)
const mediaStream = ref(null)
const mediaRecorder = ref(null)
const recordedChunks = ref([])

const previewUrl = ref(null)
const mediaType = ref('image')
const isCameraActive = ref(false)
const isRecording = ref(false)
const mediaMode = ref('photo')
const mediaItems = ref([])

// 文件处理方法
const handleFileSelect = (event) => {
  const files = event.target.files
  if (!files || mediaItems.value.length >= 6) return

  const remaining = 6 - mediaItems.value.length
  const newItems = Array.from(files)
    .slice(0, remaining)
    .map(file => ({
      url: URL.createObjectURL(file), // 预览用临时 URL
      type: file.type.startsWith('image') ? 'image' : 'video',
      rawFile: file // 保存原始文件对象
    }))

  mediaItems.value = [...mediaItems.value, ...newItems]
}

// 删除方法
const removeMedia = (index) => {
  URL.revokeObjectURL(mediaItems.value[index].url)
  mediaItems.value.splice(index, 1)
}

// 清空预览
const clearPreview = () => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
    previewUrl.value = null
  }
}

// 导航返回
const goBack = () => {
  router.push('/profile')
}

// 媒体选择处理
const openMediaPicker = () => {
  fileInput.value.click()
}

// 摄像头功能
const startCamera = async (mode) => {
  try {
    mediaMode.value = mode
    mediaStream.value = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'environment',
        width: { ideal: 1920 },
        height: { ideal: 1080 }
      },
      audio: mode === 'video'
    })

    isCameraActive.value = true
    await nextTick()
    videoPreview.value.srcObject = mediaStream.value
  } catch (error) {
    console.error('摄像头访问失败:', error)
    alert('无法访问摄像头，请检查权限设置')
  }
}

const capturePhoto = () => {
  const canvas = document.createElement('canvas')
  const video = videoPreview.value
  canvas.width = video.videoWidth
  canvas.height = video.videoHeight
  canvas.getContext('2d').drawImage(video, 0, 0)

  previewUrl.value = canvas.toDataURL('image/jpeg')
  stopCamera()
}

const toggleRecording = () => {
  if (isRecording.value) {
    stopRecording()
  } else {
    startRecording()
  }
}

const startRecording = () => {
  recordedChunks.value = []
  mediaRecorder.value = new MediaRecorder(mediaStream.value, {
    mimeType: 'video/webm; codecs=vp9'
  })

  mediaRecorder.value.ondataavailable = (e) => {
    if (e.data.size > 0) recordedChunks.value.push(e.data)
  }

  mediaRecorder.value.onstop = () => {
    const blob = new Blob(recordedChunks.value, { type: 'video/webm' })
    previewUrl.value = URL.createObjectURL(blob)
    stopCamera()
  }

  mediaRecorder.value.start()
  isRecording.value = true
}

const stopRecording = () => {
  mediaRecorder.value.stop()
  isRecording.value = false
}

const stopCamera = () => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach(track => track.stop())
    mediaStream.value = null
  }
  isCameraActive.value = false
  isRecording.value = false
}

onBeforeUnmount(() => {
  stopCamera()
  clearPreview()
})

// 修正后的发布方法
const pulish = async () => {
  // 验证基础内容
  const description = document.querySelector('.description-text').innerText.trim()
  if (!description && mediaItems.value.length === 0) {
    return alert('内容或媒体文件不能为空')
  }

  // 检查所有媒体项是否都有有效的 rawFile
  const invalidMediaItems = mediaItems.value.filter(item => !item.rawFile)
  if (invalidMediaItems.length > 0) {
    console.error('无效的媒体文件:', invalidMediaItems)
    return alert('某些媒体文件无效，请重新选择')
  }
  // 准备表单数据
  const formData = new FormData()
  formData.append('description', description)
  formData.append('topic', '旅行中的你')
 
  formData.append('userId', JSON.parse(localStorage.getItem('userInfo')).id)
  // 添加媒体文件
  mediaItems.value.forEach((item, index) => {
    if (item.rawFile) {
      formData.append(`media`, item.rawFile) // 使用字段数组形式
    }
  })

  try {
    const response = await request({
      url: '/api/publish',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data' // 必须设置
      }
    })

    console.log('发布成功:', response)
    // 清空内容
    mediaItems.value = []
    document.querySelector('.description-text').innerText = ''
    router.push('/profile').then(() => {
     
    })
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败: ' + (error.response?.data?.message || '网络错误'))
  }
}
</script>

<style scoped>
.create-post {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  max-width: 414px;
  margin: 0 auto;
  min-height: 100vh;
  background: linear-gradient(to bottom right, #e9d5ff, #fff1f2);
  position: relative;
}

.description-text[contenteditable="true"] {
  cursor: text;
  padding: 8px;
  transition: all 0.2s;
  border: 1px solid transparent;
  border-radius: 4px;
}

/* 悬停效果 */
.description-text[contenteditable="true"]:hover {
  border-color: #e0e0e0;
}

/* 聚焦效果 */
.description-text[contenteditable="true"]:focus {
  outline: none;
  border-color: #69b7ff;
  box-shadow: 0 0 8px rgba(105, 183, 255, 0.3);
  background: rgba(245, 245, 245, 0.5);
}

/* 状态栏样式 */
.status-bar {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  color: #000;
  font-weight: bold;
}

.status-icons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.battery {
  background-color: #4ade80;
  padding: 2px 4px;
  border-radius: 10px;
  font-size: 12px;
  color: white;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.back-button {
  background: none;
  border: none;
  font-size: 24px;
  color: #333;
  cursor: pointer;
  padding: 8px;
}

.publish-button {
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 20px;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #666;
}

/*上传图片 */
.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-top: 12px;
}

.image-item {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  /* 保持正方形 */
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.image-item img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #ddd;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-box:hover {
  border-color: #69b7ff;
  background: rgba(105, 183, 255, 0.05);
}

.delete-button {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 20px;
  height: 20px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}


/* 主要内容区样式 */
.content-area {
  padding: 16px;
}

.topic-tag {
  display: inline-flex;
  align-items: center;
  background-color: #e0e7ff;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  color: #6366f1;
  margin-bottom: 16px;
}

.hash {
  margin-right: 4px;
  color: #818cf8;
}

.description-text {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 24px;
}

/* 媒体上传区样式 */
.media-container {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.media-item {
  position: relative;
  flex-shrink: 0;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #ddd;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-box:hover {
  border-color: #69b7ff;
  background: rgba(105, 183, 255, 0.05);
}

/* 其他样式保持不变 */

.plus-icon {
  font-size: 32px;
  color: #ccc;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
  color: #999;
}

/* 位置选择器样式 */
.location-selector {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.location-icon {
  margin-right: 12px;
  font-size: 20px;
}

.location-text {
  flex: 1;
  font-size: 14px;
  color: #666;
}

.arrow-right {
  color: #ccc;
  font-size: 20px;
}

/* 底部工具栏样式 */
.bottom-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 12px 0;
  max-width: 414px;
  margin: 0 auto;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.tool-button {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
}

.tool-icon {
  font-size: 24px;
  color: #666;
}

/* 适配 iPhone X 及以上的底部安全区域 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  .bottom-toolbar {
    padding-bottom: calc(12px + env(safe-area-inset-bottom));
  }
}
</style>